"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { mockTicketTemplates } from "@/mocks/ticket-templates"
import { TicketTemplate, TemplateStep } from "@/types/template"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  ArrowLeft,
  ArrowUp,
  ArrowDown,
  Plus,
  Trash2,
  Save,
} from "lucide-react"
import { Checkbox } from "@/components/ui/checkbox"

export default function EditTemplateForm({ template }: { template: TicketTemplate | null }) {
  const router = useRouter()
  const [steps, setSteps] = useState<TemplateStep[]>([])

  useEffect(() => {
    if (template) {
      // Deep copy steps to avoid direct mutation of mock data
      setSteps(JSON.parse(JSON.stringify(template.steps)))
    }
  }, [template])

  const handleStepChange = (
    index: number,
    field: keyof TemplateStep,
    value: string | boolean
  ) => {
    const newSteps = [...steps]
    // @ts-ignore
    newSteps[index][field] = value
    setSteps(newSteps)
  }

  const addStep = () => {
    const newStep: TemplateStep = {
      stepNumber: steps.length + 1,
      description: "新的操作步骤",
      device: "",
      action: "",
      isCritical: false,
    }
    setSteps([...steps, newStep])
  }

  const removeStep = (index: number) => {
    const newSteps = steps.filter((_, i) => i !== index)
    // Re-number the steps
    const renumberedSteps = newSteps.map((step, i) => ({ ...step, stepNumber: i + 1 }))
    setSteps(renumberedSteps)
  }

  const moveStep = (index: number, direction: "up" | "down") => {
    if (
      (direction === "up" && index === 0) ||
      (direction === "down" && index === steps.length - 1)
    ) {
      return
    }

    const newSteps = [...steps]
    const targetIndex = direction === "up" ? index - 1 : index + 1
    const temp = newSteps[index]
    newSteps[index] = newSteps[targetIndex]
    newSteps[targetIndex] = temp

    // Re-number all steps
    const renumberedSteps = newSteps.map((step, i) => ({ ...step, stepNumber: i + 1 }))
    setSteps(renumberedSteps)
  }

  const handleSave = () => {
    if (!template) return
    // TODO: Implement actual save logic to update the mock data or send to an API
    console.log("Saving updated steps for template:", template.id, steps)
    alert("模板步骤已保存！")
    // For now, we can update the mock data directly
    const templateIndex = mockTicketTemplates.findIndex(t => t.id === template.id)
    if (templateIndex !== -1) {
      mockTicketTemplates[templateIndex].steps = steps
    }
    router.push("/admin/templates")
  }

  if (!template) {
    return <div>加载中或找不到模板...</div>
  }

  return (
    <div className="space-y-6 p-4 md:p-10 pb-16">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">
            编辑模板步骤: {template.name}
          </h2>
          <p className="text-muted-foreground">
            在这里调整、添加或删除操作步骤。
          </p>
        </div>
        <div className="flex items-center space-x-2">
           <Button variant="outline" onClick={() => router.back()}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            返回
          </Button>
          <Button onClick={handleSave}>
            <Save className="mr-2 h-4 w-4" />
            保存更改
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>步骤列表</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {steps.map((step, index) => (
            <div key={index} className="flex items-start gap-4 rounded-md border p-4">
               <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground font-bold">
                {step.stepNumber}
              </div>
              <div className="flex-1 space-y-4">
                <div className="space-y-2">
                  <Label htmlFor={`desc-${index}`}>操作描述</Label>
                  <Textarea
                    id={`desc-${index}`}
                    value={step.description}
                    onChange={e =>
                      handleStepChange(index, "description", e.target.value)
                    }
                    placeholder="输入操作描述"
                  />
                </div>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                   <div className="space-y-2">
                    <Label htmlFor={`device-${index}`}>设备</Label>
                    <Input
                      id={`device-${index}`}
                      value={step.device}
                      onChange={e =>
                        handleStepChange(index, "device", e.target.value)
                      }
                       placeholder="例如: 11G隔离开关"
                    />
                  </div>
                   <div className="space-y-2">
                    <Label htmlFor={`action-${index}`}>操作</Label>
                    <Input
                      id={`action-${index}`}
                      value={step.action}
                      onChange={e =>
                        handleStepChange(index, "action", e.target.value)
                      }
                      placeholder="例如: 断电 / 验电"
                    />
                  </div>
                </div>
                 <div className="flex items-center space-x-2">
                    <Checkbox
                      id={`critical-${index}`}
                      checked={step.isCritical}
                      onCheckedChange={checked =>
                        handleStepChange(index, "isCritical", !!checked)
                      }
                    />
                    <Label htmlFor={`critical-${index}`} className="font-medium">
                      关键步骤
                    </Label>
                  </div>
              </div>
              <div className="flex flex-col gap-2">
                <Button
                  size="icon"
                  variant="outline"
                  onClick={() => moveStep(index, "up")}
                  disabled={index === 0}
                >
                  <ArrowUp className="h-4 w-4" />
                  <span className="sr-only">Up</span>
                </Button>
                <Button
                  size="icon"
                  variant="outline"
                  onClick={() => moveStep(index, "down")}
                  disabled={index === steps.length - 1}
                >
                  <ArrowDown className="h-4 w-4" />
                   <span className="sr-only">Down</span>
                </Button>
                 <Button
                  size="icon"
                  variant="destructive"
                  onClick={() => removeStep(index)}
                >
                  <Trash2 className="h-4 w-4" />
                   <span className="sr-only">Remove</span>
                </Button>
              </div>
            </div>
          ))}
           <Button variant="secondary" onClick={addStep}>
            <Plus className="mr-2 h-4 w-4" />
            添加新步骤
          </Button>
        </CardContent>
      </Card>
    </div>
  )
} 